import 'package:json_annotation/json_annotation.dart';
import 'package:on_audio_query/on_audio_query.dart';

part 'song.g.dart';

@JsonSerializable()
class Song {
  final String? id;
  final String name;
  final String artist;
  final String album;
  final String duration;
  final String? path;
  final String? albumArtUri;
  final bool isFavorite;

  const Song({
    this.id,
    required this.name,
    required this.artist,
    required this.album,
    required this.duration,
    this.path,
    this.albumArtUri,
    this.isFavorite = false,
  });

  // 从JSON创建对象
  factory Song.fromJson(Map<String, dynamic> json) => _$SongFromJson(json);

  // 转换为JSON
  Map<String, dynamic> toJson() => _$SongToJson(this);

  // 从on_audio_query的SongModel创建Song对象
  factory Song.fromAudioQuery(SongModel songModel, [String? albumArtPath]) {
    return Song(
      id: songModel.id.toString(),
      name: songModel.title.isNotEmpty ? songModel.title : '未知标题',
      artist: songModel.artist?.isNotEmpty == true ? songModel.artist! : '未知艺术家',
      album: songModel.album?.isNotEmpty == true ? songModel.album! : '未知专辑',
      duration: _formatDuration(songModel.duration ?? 0),
      path: songModel.data,
      albumArtUri: albumArtPath, // 使用传入的专辑封面路径
    );
  }

  // 创建副本，用于更新某些字段
  Song copyWith({
    String? id,
    String? name,
    String? artist,
    String? album,
    String? duration,
    String? path,
    String? albumArtUri,
    bool? isFavorite,
  }) {
    return Song(
      id: id ?? this.id,
      name: name ?? this.name,
      artist: artist ?? this.artist,
      album: album ?? this.album,
      duration: duration ?? this.duration,
      path: path ?? this.path,
      albumArtUri: albumArtUri ?? this.albumArtUri,
      isFavorite: isFavorite ?? this.isFavorite,
    );
  }

  // 格式化时长：毫秒转换为 mm:ss 格式
  static String _formatDuration(int durationMs) {
    final seconds = durationMs ~/ 1000;
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  // 获取时长的毫秒数
  int get durationMs {
    final parts = duration.split(':');
    if (parts.length == 2) {
      final minutes = int.tryParse(parts[0]) ?? 0;
      final seconds = int.tryParse(parts[1]) ?? 0;
      return (minutes * 60 + seconds) * 1000;
    }
    return 0;
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Song &&
          runtimeType == other.runtimeType &&
          id == other.id &&
          name == other.name &&
          artist == other.artist;

  @override
  int get hashCode => id.hashCode ^ name.hashCode ^ artist.hashCode;

  @override
  String toString() {
    return 'Song(id: $id, name: $name, artist: $artist, album: $album, duration: $duration)';
  }
} 